package com.viethp.mt.activities;

import java.util.List;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.viethp.mt.common.CommonHelper;
import com.viethp.mt.common.GlobalVariables;
import com.viethp.mt.mapoverlay.MyItemizedOverlay;
import com.viethp.mt.objects.ApplyPostResponse;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;

public class AItemDetails extends MapActivity implements OnClickListener {

	private static final String ITEM_ID = "id";
	// private static final String ITEM_USER_ID = "user_id";
	// private static final String ITEM_USERNAME = "username";
	private static final String ITEM_TITLE = "title";
	private static final String ITEM_DESCRIPTION = "description";
	private static final String ITEM_EXP = "expired";
	private static final String ITEM_PRICE = "price";
	private static final String ITEM_LON = "longitude";
	private static final String ITEM_LAT = "latitude";
	private static final String ITEM_IMG_LINK = "imgLink";
	private static final String ITEM_MAX_BUDGET = "max_budget";
	private static final String ITEM_TOTAL_BIDDER = "total_bidder";

	private Button btn_back, btn_apply;
	private String item_id, title, desc, exp, price, imgLink, set_price,
			total_bidder, max_budget, lon, lat;
	// private String user_id,username;
	private TextView tv_title, tv_desc, tv_exp, tv_price, tv_post_total_bidder,
			tv_post_max_budget;
	private ImageView img;
	private EditText edt_set_price;

	MapController mControl;
	GeoPoint GeoP;
	MapView mapV;
	private Drawable items;
	private List<Overlay> mapOverlays;
	private MyItemizedOverlay itemizedOverlay;

	private ProgressDialog progressDialog;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.a_item_details);

		mapV = (MapView) findViewById(R.id.mapView);
		mapV.displayZoomControls(true);
		mapV.setBuiltInZoomControls(true);

		mapV.setTraffic(true);
		mapV.setPressed(false);
		mapV.setClickable(false);

		Intent extras = getIntent();
		initComponents();
		setOnClickListener();

		item_id = extras.getStringExtra(ITEM_ID);
		// user_id = extras.getStringExtra(ITEM_USER_ID);
		// username = extras.getStringExtra(ITEM_USERNAME);
		title = extras.getStringExtra(ITEM_TITLE);
		desc = extras.getStringExtra(ITEM_DESCRIPTION);
		exp = extras.getStringExtra(ITEM_EXP);
		price = extras.getStringExtra(ITEM_PRICE);
		total_bidder = extras.getStringExtra(ITEM_TOTAL_BIDDER);
		max_budget = extras.getStringExtra(ITEM_MAX_BUDGET);
		imgLink = extras.getStringExtra(ITEM_IMG_LINK);
		lon = extras.getStringExtra(ITEM_LON);
		lat = extras.getStringExtra(ITEM_LAT);
		CommonHelper.showToast(this, item_id);
		setInfo();
		setMap();
	}

	public void initComponents() {
		btn_back = (Button) findViewById(R.id.btn_back);
		btn_apply = (Button) findViewById(R.id.btn_post_apply);

		tv_post_total_bidder = (TextView) findViewById(R.id.tv_post_total_bidder);
		tv_post_max_budget = (TextView) findViewById(R.id.tv_post_max_budget);

		tv_title = (TextView) findViewById(R.id.tv_post_title);
		tv_exp = (TextView) findViewById(R.id.tv_post_exp);
		tv_price = (TextView) findViewById(R.id.tv_post_price);
		tv_desc = (TextView) findViewById(R.id.tv_post_desc);
		img = (ImageView) findViewById(R.id.img_post_image);

		progressDialog = new ProgressDialog(AItemDetails.this);
		progressDialog.setCancelable(false);
	}

	public void setOnClickListener() {
		btn_back.setOnClickListener(this);
		btn_apply.setOnClickListener(this);
	}

	public void setInfo() {
		tv_title.setText(title);
		tv_exp.setText(CommonHelper.timeLeft(Long.parseLong(exp)));
		tv_price.setText("$"+price);
		tv_desc.setText(desc);
		tv_post_total_bidder.setText(total_bidder);
		tv_post_max_budget.setText("$"+max_budget);
		Bitmap bm = CommonHelper.getImageBitmap(imgLink);
		img.setImageBitmap(bm);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back:
			this.finish();
			break;
		case R.id.btn_post_apply:
			DialogApplyPost();
			break;
		default:
			break;
		}

	}

	// set price
	public void DialogApplyPost() {

		LayoutInflater layoutInflater = (LayoutInflater) getApplicationContext()
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		final View view = layoutInflater.inflate(R.layout.dialog_set_price,
				null);

		edt_set_price = (EditText) view.findViewById(R.id.edt_set_price);
		edt_set_price.setHint("Set your price");
		edt_set_price.setInputType(InputType.TYPE_CLASS_NUMBER);

		final Dialog dia = new Dialog(this);
		dia.setContentView(view);
		dia.setTitle("Set your price");
		dia.getWindow().setLayout(LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT);
		dia.setCancelable(false);
		dia.show();

		final Button btn_change = (Button) view.findViewById(R.id.btn_change);

		if (String.valueOf(edt_set_price.getText()).equals(""))
			btn_change.setEnabled(false);
		edt_set_price.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				if (String.valueOf(edt_set_price.getText()).equals(""))
					btn_change.setEnabled(false);
				else
					btn_change.setEnabled(true);
			}
		});

		btn_change.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				set_price = edt_set_price.getText().toString().trim();
				Log.d("phone", set_price);
				doSetPrice();
				dia.dismiss();
			}
		});
		Button btn_cancel = (Button) view.findViewById(R.id.btn_cancel);
		btn_cancel.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dia.dismiss();

			}
		});
	}

	public void doSetPrice() {
		if (CommonHelper.isNetworkAvailable(this)) {
			startCallService();
		} else
			CommonHelper.showWarning(AItemDetails.this,
					getString(R.string.netstate));
	}

	public void startCallService() {
		progressDialog.setMessage(getString(R.string.pleasewait));
		progressDialog.show();

		new Thread(new Runnable() {

			@Override
			public void run() {
				Message message = new Message();
				message.obj = callService();
				handlerChangePhone.sendMessage(message);

			}
		}).start();
	}

	private ApplyPostResponse callService() {

		SoapObject userRequest = new SoapObject(GlobalVariables.WS_NAMESPACE,
				GlobalVariables.WS_METHOD_APPLY_POST);
		userRequest.addProperty("user_id",
				CommonHelper.getUserLogin(AItemDetails.this).getId());
		userRequest.addProperty("item_id", item_id);
		userRequest.addProperty("price", set_price);

		SoapObject request = new SoapObject(GlobalVariables.WS_NAMESPACE,
				GlobalVariables.WS_METHOD_APPLY_POST);
		request.addProperty(GlobalVariables.WS_METHOD_APPLY_POST, userRequest);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.setOutputSoapObject(request);

		HttpTransportSE androidHttpTransport = new HttpTransportSE(
				GlobalVariables.WS_ENDPOINT,
				GlobalVariables.WS_CONNECTTION_TIME_OUT);
		SoapObject results = null;
		try {
			androidHttpTransport.call(GlobalVariables.WS_NAMESPACE
					+ GlobalVariables.WS_METHOD_APPLY_POST, envelope);
		} catch (Exception e) {
			try {
				androidHttpTransport.call(GlobalVariables.WS_NAMESPACE
						+ GlobalVariables.WS_METHOD_APPLY_POST, envelope);
			} catch (Exception e1) {
				e1.printStackTrace();
				return null;

			}
		}
		try {
			results = (SoapObject) envelope.getResponse();
		} catch (SoapFault ex3) {
			ex3.printStackTrace();
			return null;
		}

		return new ApplyPostResponse(results);

	}

	private Handler handlerChangePhone = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			progressDialog.dismiss();

			if (msg.obj != null) {
				ApplyPostResponse response = (ApplyPostResponse) msg.obj;
				if (response.getErrorCode() != null) {
					CommonHelper.showWarning(AItemDetails.this, response
							.getErrorCode().getErrMsg());
				} else {
					CommonHelper.showWarning(AItemDetails.this,
							"Apply successful");
					max_budget = String.valueOf(response.getMaxBudget());
					total_bidder = String.valueOf(response.getTotalBidder());
					tv_post_max_budget.setText(max_budget);
					tv_post_total_bidder.setText(total_bidder);
				}

			} else {
				CommonHelper.showWarning(AItemDetails.this,
						getString(R.string.disconnect));
			}

		};
	};

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	public void setMap() {
		GeoP = new GeoPoint((int) (Double.parseDouble(lat) * 1E6),
				(int) (Double.parseDouble(lon) * 1E6));

		OverlayItem item = new OverlayItem(new GeoPoint(
				(int) (Double.parseDouble(lat) * 1E6),
				(int) (Double.parseDouble(lon) * 1E6)), title, "$" + price);
		mapOverlays = mapV.getOverlays();
		items = this.getResources().getDrawable(R.drawable.pin_want);
		itemizedOverlay = new MyItemizedOverlay(items, mapV);
		itemizedOverlay.addOverlay(item);
		mapOverlays.add(itemizedOverlay);
		mapV.postInvalidate();

		mControl = mapV.getController();
		mControl.animateTo(GeoP);
		mControl.setZoom(15);
		// mapV.invalidate();
	}
}
